import React from 'react'
import { Grid, List } from 'antd-mobile'
import PropTypes from 'prop-types'

class AvatarSelector extends React.Component {
  constructor () {
    super()
    this.state = {
      text: ''
    }
  }
  static propTypes = {
    selectAvatar: PropTypes.func.isRequired
  }
  componentDidMount () {
    // 解决 ant design grid 组件的 bug
    setTimeout(function () {
      window.dispatchEvent(new Event('resize'))
    }, 0)
  }
  render () {
    let avatarList = 'boy,man,girl,woman,bull,chick,crab,hedgehog,hippopotamus,koala,lemur,pig,tiger,whale,zebra'.split(',').map(v => ({icon: require(`../../assets/image/${v}.png`), text: v}))
    // 这里 require 异步执行，会导致第一次加载出不来
    let gridHeader = this.state.text ? <div><span>已选择头像</span><img style={{width: '20px', verticalAlign: 'middle'}} src={this.state.icon} alt={this.state.text}/></div> : <div>请选择头像</div>
    return (
      <div>
        <List renderHeader={() => gridHeader}>
          <Grid data={avatarList} columnNum={4} isCarousel onClick={ele => {
            this.setState(ele)
            this.props.selectAvatar(ele.text)
          }}/>
        </List>
      </div>
    )
  }
}

export default AvatarSelector